package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"unit8-exam/cache"
	"unit8-exam/models"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var list []models.Article
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Debug().Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	var total int64
	models.DB.Model(list).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"data":  list,
		"msg":   "列表成功",
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var detail models.Article
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Where("id=?", id).Debug().First(&detail)
		jsonData, _ := json.Marshal(detail)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &detail)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": detail,
		"msg":  "详情成功",
	})
	return
}
func Like(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Article{
		Title:   title,
		Content: content,
	}
	models.DB.Create(&data).Debug()
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "收藏成功",
	})
	return
}
